/**
 * @FileName: SkuController.java
 * @Author熊诗言
 * @Description:SkuController
 * @Date 2016年4月18日 上午9:27:19
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.admin.product;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.controller.admin.BaseAdminController;
import cn.hpclub.server.model.product.Sku;
import cn.hpclub.server.model.product.SkuOpt;
import cn.hpclub.server.service.product.SkuService;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.QueryHelper;
import cn.hpclub.server.validator.admin.product.SkuValidator;

public class SkuController extends BaseAdminController<Sku>{
    private static Logger logger = LoggerFactory.getLogger(SkuController.class);

    /**
     * 
     * @Title: list
     * @Description:Sku列表
     */
    public void list(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();

        QueryHelper helper = SkuService.service.getQueryHelper(searchInfo);
        logger.debug("sql:" + helper.getSelect() + helper.getSqlExceptSelect());

        findByPageForSearch(helper.getSelect(), helper.getSqlExceptSelect());
        setAttrs(searchInfo);
        render("/admin/sku_list.tpl");
    }

    /**
     * 
     * @Title: add
     * @Description:添加页面
     */
    public void add(){

        // Sku sku = new Sku();
        // setAttr("sku", sku);
        // setAttr("opts", new ArrayList<SkuOpt>());
        render("/admin/sku_input.tpl");
    }

    /**
     * 
     * @Title: edit
     * @Description:编辑页面
     */
    public void edit(){
        int skuId = getParaToInt("id");
        // 准备当前编辑的属性集
        Sku sku = Sku.dao.findById(skuId);
        setAttr("sku", sku);
        // 准备本sku的所有的opt
        List<SkuOpt> opts = SkuOpt.dao.find("select * from sku_opt o where sku_id=? order by id", skuId);
        setAttr("opts", opts);
        render("/admin/sku_input.tpl");
    }

    /**
     * 
     * @Title: save
     * @Description:保存Sku
     */
    @Before({ Tx.class, SkuValidator.class })
    public void save(){
        Sku sku = getModel(Sku.class);
        int userId = InterfaceUtil.getAdminId();
        sku.set("operated_by", userId);
        sku.set("operated_time", new Date());
        boolean isAdd = getParaToBoolean("isAdd");
        // 这是新增的opt
        String[] optNewNames = getParaValues("opts");
        // 获取以前有的opt
        Enumeration<String> names = getParaNames();
        Map<String, String> optMap = parsePara(names);

        SkuService.service.saveOrUpdate(sku, optNewNames, optMap, isAdd);
        redirect("/sku/list");
    }

    /**
     * @Title: parsePara
     * @Description:从参数中过滤出以opts_开头的 ，将其放入一个HashMap
     * @param names
     * @return Map<String,String>
     */

    private Map<String, String> parsePara(Enumeration<String> names){
        Map<String, String> optMap = new HashMap<String, String>();
        String prefix = "opts_";
        while(names.hasMoreElements()){
            String name = names.nextElement();
            if(name.startsWith(prefix)){// opts_id
                optMap.put(name.substring(name.indexOf("_") + 1), getPara(name));
            }
        }
        return optMap;
    }

    /**
     * @Title: delete
     * @Description:删除及维护Sku相关数据表
     */
    @Before(Tx.class)
    public void delete(){
        Integer[] ids = getParaValuesToInt("ids");
        // 删除attr_set_sku中的记录
        SkuService.service.deleteByIds(ids);
        // 删除sku_opt中的记录
        SkuService.service.deleteSkuoptBySku(ids);
        // 删除attr_set表中的记录
        deleteById("sku");
    }

    /**
     * 
     * @Title: changeStatus
     * @Description:改变属性集的状态，是否启用
     */
    @Before(Tx.class)
    public void changeStatus(){
        String id = getPara("id");
        String targetStatus = getPara("target_status");
        boolean success = SkuService.service.changeStatus(id, targetStatus);
        if(success){
            if(StrKit.notBlank(targetStatus) && targetStatus.equalsIgnoreCase("1")){
                ajaxJsonSuccessMessage("已启用");
            } else{
                ajaxJsonSuccessMessage("已停用");
            }
        } else{
            ajaxJsonErrorMessage("操作失败");
        }
    }

    /**
     * 
     * @Title: listOpt
     * @Description:展示sku可选属性值页面
     */
    public void listOpt(){
        String id = getPara(0);
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        Page<SkuOpt> skuopts = SkuService.service.getOptsById(getParaToInt(PAGE_NUMBER, 1), //
                                                              getParaToInt(PAGE_SIZE, 10), //
                                                              id, searchInfo);
        setAttr(PAGER, skuopts);
        setAttr("sku", Sku.dao.findById(id));
        render("/admin/skuopt_list.tpl");
    }

    /**
     * 
     * @Title: addOpt
     * @Description:添加sku_opt页面
     */
    public void addOpt(){
        setAttr("sku", Sku.dao.findById(getPara("skuId")));
        render("/admin/skuopt_input.tpl");
    }

    /**
     * 
     * @Title: edit
     * @Description:编辑sku_opt页面
     */
    public void editOpt(){
        setAttr("sku", Sku.dao.findById(getPara("skuId")));
        // 准备当前编辑的属性集
        SkuOpt skuopt = SkuOpt.dao.findById(getPara("id"));
        setAttr("skuOpt", skuopt);
        render("/admin/skuopt_input.tpl");
    }

    /**
     * 
     * @Title: save
     * @Description:保存Sku_opt
     */
    @Before(Tx.class)
    public void saveOpt(){
        SkuOpt skuopt = getModel(SkuOpt.class);
        int userId = InterfaceUtil.getAdminId();
        skuopt.set("operated_by", userId);
        skuopt.set("operated_time", new Date());
        boolean isAdd = getParaToBoolean("isAdd");
        SkuService.service.saveOrUpdate(skuopt, isAdd);
        redirect("/sku/listOpt/" + getPara("skuOpt.sku_id"));
    }

    /**
     * @Title: delete
     * @Description:删除及维护Sku相关数据表
     */
    @Before(Tx.class)
    public void deleteOpt(){
        deleteById("sku_opt");
    }

    /**
     * 
     * @Title: changeStatus
     * @Description:改变属性集的状态，是否启用
     */
    @Before(Tx.class)
    public void changeOptStatus(){
        String id = getPara("id");
        String targetStatus = getPara("target_status");
        boolean success = SkuService.service.changeOptStatus(id, targetStatus);
        if(success){
            if(StrKit.notBlank(targetStatus) && targetStatus.equalsIgnoreCase("1")){
                ajaxJsonSuccessMessage("已启用");
            } else{
                ajaxJsonSuccessMessage("已停用");
            }
        } else{
            ajaxJsonErrorMessage("操作失败");
        }
    }

    /**
     * @Title: getskuinfo
     * @Description:根据分类对应的属性集ID获取商品可选sku和skuopt信息 void
     */
    public void getskuinfo(){
        List<Record> skuinfo = SkuService.service.getSkuInfo();
        renderJson(JsonKit.toJson(skuinfo));
    }

}
